package logic

import (
	"cart_srv/cartsrv"
	"cart_srv/internal/svc"
	"cart_srv/models/mysql"
	"cart_srv/models/redis"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCartLogic) AddCart(in *cartsrv.AddCartRequest) (*cartsrv.AddCartResponse, error) {
	// todo: add your logic here and delete this line
	var good mysql.Good
	err := good.FindGoods(int(in.GoodsId))
	if err != nil {
		return nil, fmt.Errorf("商品查询失败")
	}
	if good.ID == 0 {
		return nil, fmt.Errorf("商品不存在")
	}
	if in.Num > redis.GetGoodsStock(int(in.GoodsId)) {
		return nil, fmt.Errorf("商品库存不足")
	}
	redis.AddCart(int(in.UserId), int(in.GoodsId), int(in.Num), good.Title, good.Cover, good.Price)
	return &cartsrv.AddCartResponse{Id: int64(good.ID)}, nil
}
